import Vue from 'vue';
import App from './App';
import router from './router';
import axios from 'axios';
import ElementUI from 'element-ui';
//import 'element-ui/lib/theme-default/index.css'; // 默认主题
import '../static/css/theme-green/index.css'; // 浅绿色主题
import websdk from 'easemob-websdk'


import '../static/css/animate.min.css'
import '../static/css/main.css'
import '../static/js/jquery.hDialog.min'

import "babel-polyfill";
import './mock/index.js';
import $ from 'jquery';
import AMap from 'vue-amap';
import store from './store/index' //引入userstore，


let webIM = window.WebIM = websdk
Vue.prototype.$WebIM = webIM
const imConn = new webIM.connection({  //创建连接
    isMultiLoginSessions: webIM.config.isMultiLoginSessions,
    https: typeof webIM.config.https === 'boolean' ? webIM.config.https : location.protocol === 'https:',
    url: webIM.config.xmppURL,
    isAutoLogin: true,
    heartBeatWait: webIM.config.heartBeatWait,
    autoReconnectNumMax: webIM.config.autoReconnectNumMax,
    autoReconnectInterval: webIM.config.autoReconnectInterval,
    apiUrl: webIM.config.apiURL
})
const options = {
  apiUrl: WebIM.config.apiURL,
  user: '15594818160',
  pwd: '123456',
  appKey: WebIM.config.appkey
}
Vue.prototype.$imConn = imConn
Vue.prototype.$imoption = options


Vue.use(AMap);
AMap.initAMapApiLoader({
    key: '1a25480e49789bf3e479544af049601c',
    plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor', 'AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.PolyEditor', 'AMap.CircleEditor']
        //plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor']
});

Vue.use(ElementUI);
Vue.prototype.$axios = axios;
new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app');
import validatorPlugin from "./mock/cy-validator-plugin"
Vue.use(validatorPlugin);
//import AMap from 'vue-amap';


// Vue.prototype.$host = 'http://172.17.1.157:8080';

// Vue.prototype.$host = 'http://172.17.1.158:8080';


// Vue.prototype.$host = 'http://172.17.37.231:8080';
Vue.prototype.$host = 'http://www.chenyekeji.com/21market';

//配置axios
var instance = axios.create({
    baseURL: Vue.prototype.$host,
    timeout: 1000,
});
Vue.prototype.$axios = instance
    //页面主标题
Vue.prototype.$title = localStorage.getItem("main_title");

Date.prototype.format = function(format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}

//format("yyyy-MM-dd h:m:s");
Vue.prototype.myajax = function(url, data, success, isFrist) {
    let self = this;
    //如果是第一次发送，若token失效，更新token
    if (!isFrist || isFrist != true) {
        isFrist = false;
    }
    var token = localStorage.getItem('user_token');
    $.ajax({
        type: 'POST',
        url: Vue.prototype.$host + "/admin" + url,
        dataType: 'json',
        async: false,
        crossDomain: true,
        traditional: true, //传递数组
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(data),
        headers: {
            "Authorization": token,
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials': true,
            'Access-Control-Allow-Headers': "x-requested-with"
        },
        success: function(response) {
            if (response.code == 1001 && !isFrist) {
                $.ajax({
                    type: 'POST',
                    url: Vue.prototype.$host + "/login",
                    dataType: 'json',
                    async: false,
                    crossDomain: true,
                    headers: {
                        "Authorization": "Basic " + localStorage.getItem("App_Http_Config_2387fei89354hng4"),
                        'Access-Control-Allow-Origin': '*',
                        'Access-Control-Allow-Credentials': true,
                        'Access-Control-Allow-Headers': "x-requested-with"
                    },
                    success: function(res) {
                        localStorage.setItem('user_token', res.data);
                        Vue.prototype.myajax(url, data, success, true);
                    },
                    error: function(xhr, textStatus, errorThrown) {
                        if (xhr.status == 401) {
                            $.tooltip("用户名或密码错误", 3000);
                        } else if (xhr.status == 403) {
                            $.tooltip("用户已被禁用", 3000);
                        } else {
                            $.tooltip("网络服务器错误", 3000);
                        }
                        window.location.hash = "login";
                    },
                    beforeSend: function(xhr) {
                        xhr.withCredentials = true
                    }
                });
            } else {
                success(response);
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            if (xhr.status == 401 || xhr.status == 403) {
                $.tooltip("登录时间已过期，请重新登录哦", 3000);
                setTimeout(function() {
                    self.$router.push('/login');
                }, 1000);
            } else if (xhr.status == 500) {
                $.tooltip("服务器错误", 3000);
            } else {
                $.tooltip("网络或服务器错误", 3000);
            }
        },
        beforeSend: function(xhr) {
            xhr.withCredentials = true
        }
    });
}

Vue.prototype.uploadDialog = false;

Vue.prototype.uploadImg = function(ele, showele) {
    var backimg;
    var self = this;
    var $input = $(ele);
    //var $tar=$(tar);
    var $showele = $(showele)
    console.log($input.val());
    var file = $input.get()[0].files[0];
    var size = file.size;
    if (size > 1024 * 1024 * 5) {
        $tar.val("");
        $.tooltip("上传图片不能大于5m", 3000);
        return;
    }
    //判断上传文件的后缀名
    var imgPath = $input.val();
    var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
    if (strExtension != 'jpg' && strExtension != 'gif' && strExtension != 'png' && strExtension != 'bmp') {
        $.tooltip("请选择图片", 3000);
        return;
    }
    var formData = new FormData();
    var name = $input.val();
    formData.append("file", file);
    formData.append("name", name);
    Vue.prototype.uploadDialog = true;

    $.ajax({
        type: 'POST',
        url: Vue.prototype.$host + "/image/upload",
        dataType: 'json',
        async: false,
        crossDomain: true,
        //traditional :true,//传递数组
        data: formData,
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        success: function(data) {
            //self.userData=data.data;
            //self.total=data.total;
            var url = Vue.prototype.$host+data.data
            backimg = data.data;
            console.log(data)
            console.log(url)
            $showele.attr('src', url);
            $input.wrap('<form>').closest('form').get(0).reset();
            $input.unwrap();

            Vue.prototype.uploadDialog = false;
        },
        error: function(xhr, textStatus, errorThrown) {
            Vue.prototype.uploadDialog = false;

            if (xhr.status == 401 || xhr.status == 403) {
                $.tooltip("登录时间已过期，请重新登录哦", 3000);
                setTimeout("self.$router.push('/readme')", 1000);
            } else if (xhr.status == 500) {
                $.tooltip("服务器错误", 3000);
            } else {
                $.tooltip("网络或服务器错误", 3000);
            }
        },
        beforeSend: function(xhr) {
            xhr.withCredentials = true
        }
    });
    return backimg;
}

//------------------------------分页
var that = this;
Vue.prototype.$page = {
    pageNumber: 1,
    pageSize: 10,
    total: 0,
    selectPage: [10, 20, 30, 40, 50]
};
//分页方法
Vue.prototype.$handleCurrentChange = function(val) { //翻页
    this.$page.pageNumber = val;

};
Vue.prototype.$handleSizeChange = function(val) { //每页数量
    this.$page.pageSize = val;
};
Vue.prototype.$handleSelectionChange = function(val) {

}

//---------------------------日期工具类
//日期相关工具类
Vue.prototype.dateUtils = {
    tomorrowBefore: {
        disabledDate: function(time) {
            var t = Date.now() + 24 * 60 * 60 * 1000;
            return time.getTime() < t - 8.64e7;
        }
    }
}

//--------------------------URL工具类
Vue.prototype.dataSave = {
    put: function(k, v) {
        window.sessionStorage.setItem(k, v);
    },
    get: function(k) {
        return window.sessionStorage.getItem(k);
    },
    remove: function(k) {
        window.sessionStorage.removeItem(k);
    }
}

